<script setup lang="ts">
import { ref, computed, onMounted } from 'vue';
import type { Patient, PatientList } from '@/types/user'
import { getPatientList, addPatient, editPatient, delPatient } from '@/services/patient';
import { showFailToast, showSuccessToast, showToast } from 'vant';
import { showConfirmDialog } from 'vant';
import { nameRules, idCardRules } from "@/utils/rules"
import { useRoute } from 'vue-router';
import { useConsultStore } from '@/stores'
import router from '@/router'
const store = useConsultStore()
const options = ref([{ label: '男', value: 1 }, { label: '女', value: 0 }])
const show = ref(false)
const showPopup = () => {
    show.value = true
    patient.value = {
        id: '',
        name: '',
        gender: 1,
        idCard: '',
        defaultFlag: false
    }

}


const patient = ref<Patient>({
    id: '',
    name: '',
    gender: 1,
    idCard: '',
    defaultFlag: false
})

const form = ref(null)
const onSubmit = async () => {
    const res = await form.value?.validate()
    if (res === undefined) {
        //校验身份证和所选的性别是否一致
        // gender=0女 1男 
        let sexNum = (+patient.value.idCard.slice(-2, -1)) % 2 === 0 ? 0 : 1
        if (patient.value.gender != sexNum) {
            return showFailToast('所选的性别与身份证上的性别不一致')
        }
        //没有id则是新增
        const Params = JSON.parse(JSON.stringify(patient.value))
        delete Params.genderValue
        !patient.value.id ? delete Params.id : ''
        patient.value.id ? delete Params.age : ''
        Params.defaultFlag = Params.defaultFlag ? 1 : 0
        patient.value.id ? await editPatient(Params) : await addPatient(Params)
        show.value = false
        showSuccessToast('保存成功')
        loadList()
    } else {
        return showFailToast('请填写完整表单的信息')
    }


}
const defaultFlag = ref(true)
const remove = () => {
    showConfirmDialog({
        title: '删除患者',
        message: `是否删除患者${patient.value.name}`,
    })
        .then(async () => {
            const res = await delPatient(patient.value.id)
            if (res.code == 10000) {
                show.value = false
                showSuccessToast('删除成功')
                loadList()
            } else {
                showFailToast(res.message)
            }
        })
        .catch(() => {
            // on cancel
        });
}
// 获取列表接口
const patientList = ref<PatientList>([])
const loadList = async () => {
    const res = await getPatientList()
    if (res.code == 10000) {
        patientList.value = res.data
    } else {
        showFailToast(res.message)
    }
    // 设置默认选中的ID，当你是选择患者的时候，且有患者信息的时候
    if (isChange.value && patientList.value.length) {
        const defPatient = patientList.value.find((item) => item.defaultFlag === 1)
        if (defPatient) patientId.value = defPatient.id
        else patientId.value = patientList.value[0].id
    }
}
onMounted(() => {
    loadList()
})
const formId = (val: string): string => {
    return val.slice(0, 6) + '******' + val.slice(-4)
}
const handleEdit = (item: Patient) => {
    show.value = true
    patient.value = { ...item }
    patient.value.defaultFlag = patient.value.defaultFlag ? true : false
}
// 是否是选择患者
const route = useRoute()
const isChange = computed(() => route.query.isChange === '1')
const patientId = ref<string>()
const selectedPatient = (item: Patient) => {
    if (isChange.value) {
        patientId.value = item.id
    }
}
const next = async () => {
    if (!patientId.value) return showToast('请选就诊择患者')
    store.setPatient(patientId.value)
    router.push('/consult/pay')
}
</script>



<template>
    <div class="patient-page">
        <cp-nav-bar :title="isChange ? '选择患者' : '家庭档案'"></cp-nav-bar>
        <div class="patient-change" v-if="isChange">
            <h3>请选择患者信息</h3>
            <p>以便医生给出更准确的治疗，信息仅医生可见</p>
        </div>
        <div class="patient-list">
            <div class="patient-item" v-for="(item, index) in patientList" :key="index" @click="selectedPatient(item)"
                :class="{ selected: patientId === item.id }">
                <div class="info">
                    <span class="name">{{ item.name }}</span>
                    <span class="id">{{ formId(item.idCard) }}</span>
                    <span>{{ item.genderValue }}</span>
                    <span>{{ item.age }}岁</span>
                </div>
                <div class="icon" @click="handleEdit(item)"><cp-icon name="user-edit" /></div>
                <div class="tag">默认</div>
            </div>
            <div class="patient-add" v-if="patientList.length < 6" @click="showPopup">
                <cp-icon name="user-add" />
                <p>添加患者</p>
            </div>
            <div class="patient-tip">最多可添加 6 人</div>
        </div>
        <!-- Popup弹窗展示添加/编辑家人档案 -->
        <!-- 底部按钮 -->
        <div class="patient-next" @click="next" v-if="isChange">
            <van-button type="primary" round block>下一步</van-button>
        </div>
        <!-- 使用 popup 组件 -->
        <van-popup position="right" v-model:show="show">
            <cp-nav-bar :title="patient?.id ? '编辑患者' : '添加患者'" right-text="保存" :back="() => (show = false)"
                @click-right="onSubmit">
            </cp-nav-bar>
            <van-form autocomplete="off" ref="form">
                <van-field v-model="patient.name" label="真实姓名" placeholder="请输入真实姓名" :rules="nameRules" />
                <van-field v-model="patient.idCard" label="身份证号" placeholder="请输入身份证号" :rules="idCardRules" />
                <van-field label="性别" class="pb4">
                    <!-- 单选按钮组件 -->
                    <template #input>
                        <cp-radio-btn v-model="patient.gender" :options="options"></cp-radio-btn>
                    </template>
                </van-field>
                <van-field label="默认就诊人">
                    <template #input>
                        <van-checkbox v-model="patient.defaultFlag" :icon-size="18" round />
                    </template>
                </van-field>
            </van-form>
            <!-- 删除按钮 -->
            <van-action-bar v-if="patient.id">
                <van-action-bar-button text="删除" @click="remove" />
            </van-action-bar>
        </van-popup>
    </div>

</template>

<style lang="scss" scoped>
.patient-page {
    padding: 46px 0 80px;

    :deep() {
        .van-popup {
            width: 100%;
            height: 100%;
            padding-top: 46px;
            box-sizing: border-box;
        }
    }
}

.patient-change {
    padding: 15px;

    >h3 {
        font-weight: normal;
        margin-bottom: 5px;
    }

    >p {
        color: var(--cp-text3);
    }
}

.patient-next {
    padding: 15px;
    background-color: #fff;
    position: fixed;
    left: 0;
    bottom: 0;
    width: 100%;
    height: 80px;
    box-sizing: border-box;
}

// 底部操作栏
.van-action-bar {
    padding: 0 10px;
    margin-bottom: 10px;

    .van-button {
        color: var(--cp-price);
        background-color: var(--cp-bg);
    }
}

.patient-list {
    padding: 15px;
}

.patient-item {
    display: flex;
    align-items: center;
    padding: 15px;
    background-color: var(--cp-bg);
    border-radius: 8px;
    margin-bottom: 15px;
    position: relative;
    border: 1px solid var(--cp-bg);
    transition: all 0.3s;
    overflow: hidden;

    .info {
        display: flex;
        flex-wrap: wrap;
        flex: 1;

        span {
            color: var(--cp-tip);
            margin-right: 20px;
            line-height: 30px;

            &.name {
                font-size: 16px;
                color: var(--cp-text1);
                width: 80px;
                margin-right: 0;
            }

            &.id {
                color: var(--cp-text2);
                width: 180px;
            }
        }
    }

    .icon {
        color: var(--cp-tag);
        width: 20px;
        text-align: center;
    }

    .tag {
        position: absolute;
        right: 60px;
        top: 21px;
        width: 30px;
        height: 16px;
        font-size: 10px;
        color: #fff;
        background-color: var(--cp-primary);
        border-radius: 2px;
        display: flex;
        justify-content: center;
        align-items: center;
    }

    &.selected {
        border-color: var(--cp-primary);
        background-color: var(--cp-plain);

        .icon {
            color: var(--cp-primary);
        }
    }
}

.patient-add {
    background-color: var(--cp-bg);
    color: var(--cp-primary);
    text-align: center;
    padding: 15px 0;
    border-radius: 8px;

    .cp-icon {
        font-size: 24px;
    }
}

.patient-tip {
    color: var(--cp-tag);
    padding: 12px 0;
}

.pb4 {
    padding-bottom: 4px;
}
</style>